#socket技术,socket=IP+端口
'''
1、创建套接字
s=socket.socket()
2、绑定ip+端口
s.bind(('ip',端口))
3、
'''
import  socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
key = RSA.generate(2048) # 实例化密钥对，密钥长度为2048bits
# 生成的私钥公钥都是bytes的数据，这里密钥转不转str都可以 .decode()默认用utf-8把bytes转str
# 私钥 解密
private_key = key.export_key()
public_key = key.publickey().export_key()
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',8001))
s.listen()
conn,address=s.accept()
data=conn.recv(1024)
print('用户端发来了连接请求!')
s.close()

s1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s1.connect(('127.0.0.1',8002))
s1.sendall(public_key)
s1.close()

s2=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s2.bind(('127.0.0.1',8001))
s2.listen()
conn2,address2=s2.accept()
c_data=conn2.recv(1204)
print('用户端发来了加密文件，内容为：')
print(c_data)
private_key = RSA.importKey(private_key)
d_cipher = PKCS1_OAEP.new(private_key) # 解密套件
org_data = d_cipher.decrypt(c_data)
print('解密后为：')
print(org_data)
file=open(r'C:\Users\曾令杰\Desktop\3.txt','w+',encoding='utf-8')
file.write(str(org_data))

#print('收到'+str(public_key))
